<template>
  <div class="merchant-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back" @click="goBack">
        <i class="el-icon-arrow-left"></i>
      </div>
      <div class="title">商家详情</div>
      <div class="share" @click="shareMerchant">
        <i class="el-icon-share"></i>
      </div>
    </div>

    <!-- 商家信息 -->
    <div class="merchant-info">
      <div class="merchant-cover">
        <img :src="merchant.cover" alt="merchant" class="cover-img">
      </div>
      <div class="merchant-detail">
        <div class="merchant-name">{{ merchant.name }}</div>
        <div class="merchant-rating">
          <span class="rating-star" v-for="i in 5" :key="i">
            <i class="el-icon-star-on" :style="{color: i <= merchant.rating ? '#ffc300' : '#eee'}"></i>
          </span>
          <span class="rating-value">{{ merchant.rating }}</span>
          <span class="sales-volume">月售{{ merchant.sales }}单</span>
        </div>
        <div class="merchant-price">
          <span>{{ merchant.minPrice }}起送</span>
          <span class="delivery-fee">{{ merchant.deliveryFee }}配送费</span>
        </div>
        <div class="merchant-distance">
          <span>{{ merchant.distance }}</span>
          <span>{{ merchant.time }}分钟</span>
        </div>
      </div>
    </div>

    <!-- 优惠活动 -->
    <div class="promotions">
      <div class="promotion-item" v-for="(promo, index) in merchant.promotions" :key="index">
        <div class="promo-tag">{{ promo.tag }}</div>
        <div class="promo-content">{{ promo.content }}</div>
      </div>
    </div>

    <!-- 商品分类和列表 -->
    <div class="content">
      <!-- 左侧分类导航 -->
      <div class="category-nav">
        <div class="category-item" 
             v-for="(category, index) in categories" 
             :key="index" 
             :class="{ active: currentCategoryIndex === index }"
             @click="switchCategory(index)">
          <span>{{ category.name }}</span>
          <span class="count" v-if="category.count > 0">{{ category.count }}</span>
        </div>
      </div>

      <!-- 右侧商品列表 -->
      <div class="product-list">
        <div class="product-group" v-for="(category, index) in categories" :key="index">
          <div class="group-title" v-if="currentCategoryIndex === index || index === 0">
            {{ category.name }}
          </div>
          <div class="product-item" v-for="product in category.products" :key="product.id">
            <div class="product-img">
              <img v-lazy="product.imgUrl" alt="product" class="img">
            </div>
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-desc">{{ product.desc }}</div>
              <div class="product-price">
                <span class="price">¥{{ product.price }}</span>
                <span class="original-price" v-if="product.originalPrice > product.price">¥{{ product.originalPrice }}</span>
              </div>
              <div class="product-actions">
                <div class="quantity-controller" v-if="isProductInCart(product.id)">
                  <button class="decrease" @click="decreaseQuantity(product)"><i class="el-icon-minus"></i></button>
                  <span class="quantity">{{ getProductQuantity(product.id) }}</span>
                  <button class="increase" @click="increaseQuantity(product)"><i class="el-icon-plus"></i></button>
                </div>
                <button class="add-btn" v-else @click="addToCart(product)">
                  <i class="el-icon-plus"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部购物车 -->
    <div class="cart-bar">
      <div class="cart-icon">
        <i class="el-icon-shopping-cart-full"></i>
        <span class="cart-count" v-if="cartTotalCount > 0">{{ cartTotalCount }}</span>
      </div>
      <div class="cart-info">
        <div class="total-price">
          <span class="currency">¥</span>
          <span class="price">{{ cartTotalPrice.toFixed(2) }}</span>
        </div>
        <div class="min-price-tip" v-if="cartTotalPrice < merchant.minPriceAsNumber">
          还差 {{ (merchant.minPriceAsNumber - cartTotalPrice).toFixed(2) }} 元起送
        </div>
      </div>
      <div class="checkout-btn" 
           :class="{ disabled: cartTotalPrice < merchant.minPriceAsNumber }"
           @click="checkout">
        结算
      </div>
    </div>

    <!-- 购物车详情 -->
    <div class="cart-detail" v-show="showCartDetail">
      <div class="cart-header">
        <div class="title">购物车</div>
        <div class="clear-cart" @click="clearCart">清空购物车</div>
      </div>
      <div class="cart-items">
        <div class="cart-item" v-for="item in cartList" :key="item.id">
          <div class="item-name">{{ item.name }}</div>
          <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
          <div class="item-quantity">
            <button class="decrease" @click="decreaseQuantity(item)"><i class="el-icon-minus"></i></button>
            <span class="quantity">{{ item.count }}</span>
            <button class="increase" @click="increaseQuantity(item)"><i class="el-icon-plus"></i></button>
          </div>
        </div>
      </div>
      <div class="cart-footer">
        <div class="delivery-fee">配送费: ¥{{ merchant.deliveryFeeAsNumber.toFixed(2) }}</div>
        <div class="total-amount">总计: ¥{{ (cartTotalPrice + merchant.deliveryFeeAsNumber).toFixed(2) }}</div>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div class="mask" v-show="showCartDetail" @click="toggleCartDetail"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      merchant: {
        id: 1,
        name: '麦当劳（中关村店）',
        cover: 'https://picsum.photos/400/200?random=31',
        rating: 4.8,
        sales: 1234,
        minPrice: '20',
        minPriceAsNumber: 20,
        deliveryFee: '5',
        deliveryFeeAsNumber: 5,
        distance: '1.2km',
        time: '25-35',
        promotions: [
          { tag: '满减', content: '满29减5，满59减15，满99减30' },
          { tag: '赠品', content: '购买套餐送玩具' },
          { tag: '折扣', content: '单品限时8折' }
        ]
      },
      categories: [
        {
          id: 1,
          name: '招牌推荐',
          count: 4,
          products: [
            {
              id: 101,
              name: '巨无霸套餐',
              imgUrl: 'https://picsum.photos/200/200?random=101',
              price: 39.0,
              originalPrice: 49.0,
              desc: '巨无霸汉堡+中份薯条+中杯可乐',
              sales: 2345
            },
            {
              id: 102,
              name: '麦辣鸡腿堡套餐',
              imgUrl: 'https://picsum.photos/200/200?random=102',
              price: 36.0,
              originalPrice: 42.0,
              desc: '麦辣鸡腿堡+中份薯条+中杯可乐',
              sales: 1876
            },
            {
              id: 103,
              name: '板烧鸡腿堡套餐',
              imgUrl: 'https://picsum.photos/200/200?random=103',
              price: 38.0,
              originalPrice: 44.0,
              desc: '板烧鸡腿堡+中份薯条+中杯可乐',
              sales: 1543
            },
            {
              id: 104,
              name: '双层吉士汉堡套餐',
              imgUrl: 'https://picsum.photos/200/200?random=104',
              price: 32.0,
              originalPrice: 38.0,
              desc: '双层吉士汉堡+中份薯条+中杯可乐',
              sales: 1298
            }
          ]
        },
        {
          id: 2,
          name: '汉堡',
          count: 5,
          products: [
            {
              id: 201,
              name: '巨无霸',
              imgUrl: 'https://picsum.photos/200/200?random=201',
              price: 24.0,
              desc: '两片百分百纯牛肉，搭配生菜、洋葱等新鲜食材',
              sales: 3456
            },
            {
              id: 202,
              name: '麦辣鸡腿堡',
              imgUrl: 'https://picsum.photos/200/200?random=202',
              price: 21.0,
              desc: '金黄酥脆的鸡腿肉，搭配新鲜蔬菜和酱料',
              sales: 4231
            },
            {
              id: 203,
              name: '板烧鸡腿堡',
              imgUrl: 'https://picsum.photos/200/200?random=203',
              price: 22.0,
              desc: '嫩滑多汁的鸡腿肉，搭配香浓酱料和新鲜蔬菜',
              sales: 2876
            },
            {
              id: 204,
              name: '双层吉士汉堡',
              imgUrl: 'https://picsum.photos/200/200?random=204',
              price: 18.0,
              desc: '两层牛肉饼，搭配芝士、酸黄瓜和特制酱料',
              sales: 3124
            },
            {
              id: 205,
              name: '麦香鱼',
              imgUrl: 'https://picsum.photos/200/200?random=205',
              price: 17.0,
              desc: '深海鳕鱼，外酥里嫩，搭配塔塔酱和生菜',
              sales: 1987
            }
          ]
        },
        {
          id: 3,
          name: '小食',
          count: 4,
          products: [
            {
              id: 301,
              name: '薯条（中份）',
              imgUrl: 'https://picsum.photos/200/200?random=301',
              price: 11.0,
              desc: '金黄酥脆，口感细腻',
              sales: 5678
            },
            {
              id: 302,
              name: '麦辣鸡翅',
              imgUrl: 'https://picsum.photos/200/200?random=302',
              price: 14.0,
              desc: '4块装，香辣过瘾',
              sales: 4231
            },
            {
              id: 303,
              name: '上校鸡块',
              imgUrl: 'https://picsum.photos/200/200?random=303',
              price: 13.0,
              desc: '5块装，多种蘸酱可选',
              sales: 3876
            },
            {
              id: 304,
              name: '薯条（大份）',
              imgUrl: 'https://picsum.photos/200/200?random=304',
              price: 13.0,
              desc: '更大份量，满足分享',
              sales: 2765
            }
          ]
        },
        {
          id: 4,
          name: '饮料',
          count: 5,
          products: [
            {
              id: 401,
              name: '可乐（中杯）',
              imgUrl: 'https://picsum.photos/200/200?random=401',
              price: 8.0,
              desc: '清爽可口',
              sales: 6789
            },
            {
              id: 402,
              name: '雪碧（中杯）',
              imgUrl: 'https://picsum.photos/200/200?random=402',
              price: 8.0,
              desc: '柠檬口味，清新解渴',
              sales: 5432
            },
            {
              id: 403,
              name: '橙汁',
              imgUrl: 'https://picsum.photos/200/200?random=403',
              price: 10.0,
              desc: '100%纯果汁',
              sales: 3210
            },
            {
              id: 404,
              name: '冰美式',
              imgUrl: 'https://picsum.photos/200/200?random=404',
              price: 12.0,
              desc: '浓郁咖啡，口感纯正',
              sales: 2109
            },
            {
              id: 405,
              name: '热拿铁',
              imgUrl: 'https://picsum.photos/200/200?random=405',
              price: 15.0,
              desc: '香浓牛奶与咖啡的完美融合',
              sales: 1876
            }
          ]
        },
        {
          id: 5,
          name: '甜品',
          count: 3,
          products: [
            {
              id: 501,
              name: '圆筒冰淇淋',
              imgUrl: 'https://picsum.photos/200/200?random=501',
              price: 5.0,
              desc: '奶香浓郁，口感丝滑',
              sales: 7890
            },
            {
              id: 502,
              name: '草莓新地',
              imgUrl: 'https://picsum.photos/200/200?random=502',
              price: 9.0,
              desc: '香草冰淇淋搭配草莓酱和巧克力酱',
              sales: 5678
            },
            {
              id: 503,
              name: '苹果派',
              imgUrl: 'https://picsum.photos/200/200?random=503',
              price: 7.0,
              desc: '酥脆外皮包裹香甜苹果馅',
              sales: 4321
            }
          ]
        }
      ],
      currentCategoryIndex: 0,
      showCartDetail: false
    }
  },
  computed: {
    cartList() {
      return this.$store.state.cartList
    },
    cartTotalCount() {
      return this.$store.getters.cartTotalCount
    },
    cartTotalPrice() {
      return this.$store.getters.cartTotalPrice
    }
  },
  methods: {
    goBack() {
      this.$router.back()
    },
    shareMerchant() {
      // 分享功能
      this.$message.info('分享功能开发中...')
    },
    switchCategory(index) {
      this.currentCategoryIndex = index
    },
    addToCart(product) {
      this.$store.commit('addToCart', product)
      this.showCartDetail = true
    },
    increaseQuantity(product) {
      this.$store.commit('updateCartCount', { id: product.id, count: product.count + 1 })
    },
    decreaseQuantity(product) {
      if (product.count > 1) {
        this.$store.commit('updateCartCount', { id: product.id, count: product.count - 1 })
      } else {
        this.$store.commit('removeFromCart', product.id)
      }
    },
    isProductInCart(productId) {
      return this.cartList.some(item => item.id === productId)
    },
    getProductQuantity(productId) {
      const item = this.cartList.find(item => item.id === productId)
      return item ? item.count : 0
    },
    toggleCartDetail() {
      this.showCartDetail = !this.showCartDetail
    },
    clearCart() {
      this.$store.commit('clearCart')
      this.showCartDetail = false
    },
    checkout() {
      if (this.cartTotalPrice < this.merchant.minPriceAsNumber) {
        this.$message.warning(`还差 ${(this.merchant.minPriceAsNumber - this.cartTotalPrice).toFixed(2)} 元起送`)
        return
      }
      
      if (!this.$store.getters.isLoggedIn) {
        this.$router.push({ name: 'Login', query: { redirect: '/cart' } })
        return
      }
      
      this.$router.push({ name: 'Cart' })
    }
  },
  async mounted() {
    // 从API加载商家信息
    try {
      const response = await this.$axios.get(`/api/merchants/${this.$route.params.id}`)
      this.merchant = response.data
      // 处理价格为数字类型
      this.merchant.minPriceAsNumber = parseFloat(this.merchant.minPrice)
      this.merchant.deliveryFeeAsNumber = parseFloat(this.merchant.deliveryFee)
    } catch (error) {
      console.error('加载商家信息失败', error)
    }
  }
}
</script>

<style scoped>
.merchant-container {
  padding-bottom: 60px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #ff6600;
  color: white;
  height: 44px;
}

.back, .share {
  width: 30px;
  text-align: center;
  cursor: pointer;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.merchant-info {
  display: flex;
  padding: 15px;
  background-color: white;
}

.merchant-cover {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 15px;
}

.cover-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.merchant-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.merchant-name {
  font-size: 18px;
  font-weight: bold;
}

.merchant-rating {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.rating-star {
  display: flex;
}

.rating-value {
  margin-left: 5px;
}

.sales-volume {
  margin-left: 10px;
}

.merchant-price {
  display: flex;
  font-size: 12px;
  color: #666;
}

.delivery-fee {
  margin-left: 10px;
}

.merchant-distance {
  display: flex;
  font-size: 12px;
  color: #999;
}

.merchant-distance span:first-child {
  margin-right: 10px;
}

.promotions {
  background-color: white;
  margin-top: 10px;
  padding: 10px 15px;
}

.promotion-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.promotion-item:last-child {
  border-bottom: none;
}

.promo-tag {
  font-size: 12px;
  color: #ff6600;
  border: 1px solid #ff6600;
  border-radius: 2px;
  padding: 0 3px;
  margin-right: 10px;
}

.promo-content {
  font-size: 14px;
  color: #333;
}

.content {
  display: flex;
  margin-top: 10px;
  height: calc(100vh - 260px);
}

.category-nav {
  width: 80px;
  background-color: #f8f8f8;
  overflow-y: auto;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60px;
  padding: 0 5px;
  text-align: center;
  border-bottom: 1px solid #eee;
  position: relative;
  cursor: pointer;
}

.category-item.active {
  background-color: white;
  color: #ff6600;
  border-left: 2px solid #ff6600;
}

.count {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: #ff6600;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  font-size: 10px;
}

.product-list {
  flex: 1;
  background-color: white;
  overflow-y: auto;
}

.group-title {
  padding: 10px 15px;
  background-color: #f8f8f8;
  font-size: 14px;
  color: #666;
}

.product-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.product-img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 10px;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
}

.product-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
  height: 36px;
  overflow: hidden;
}

.product-price {
  display: flex;
  align-items: center;
}

.price {
  font-size: 16px;
  font-weight: bold;
  color: #ff6600;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
  margin-left: 5px;
}

.product-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #ff6600;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.quantity-controller {
  display: flex;
  align-items: center;
}

.decrease, .increase {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.quantity {
  width: 24px;
  text-align: center;
  font-size: 14px;
}

.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 50px;
  background-color: white;
  z-index: 100;
}

.cart-icon {
  width: 60px;
  height: 60px;
  border-radius: 30px;
  background-color: #666;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  top: -10px;
  left: 10px;
  cursor: pointer;
}

.cart-icon i {
  font-size: 24px;
}

.cart-count {
  position: absolute;
  top: -2px;
  right: -2px;
  background-color: #ff6600;
  color: white;
  border-radius: 50%;
  width: 20px;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 12px;
}

.cart-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 15px;
  background-color: #333;
  color: white;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
}

.currency {
  font-size: 14px;
}

.min-price-tip {
  font-size: 12px;
  color: #aaa;
}

.checkout-btn {
  width: 100px;
  background-color: #ff6600;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: pointer;
}

.checkout-btn.disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.cart-detail {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  background-color: white;
  max-height: 300px;
  overflow-y: auto;
  z-index: 101;
  transform: translateY(100%);
  transition: transform 0.3s ease-in-out;
}

.cart-detail.active {
  transform: translateY(0);
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.clear-cart {
  color: #666;
  font-size: 14px;
  cursor: pointer;
}

.cart-items {
  max-height: 200px;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.item-name {
  font-size: 14px;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  font-size: 14px;
  color: #ff6600;
}

.item-quantity {
  display: flex;
  align-items: center;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-top: 1px solid #eee;
}

.delivery-fee, .total-amount {
  font-size: 14px;
}

.total-amount {
  font-weight: bold;
  color: #ff6600;
}

.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.show {
  display: block;
}

.hide {
  display: none;
}
</style>
    